import React, { useState, useEffect, useImperativeHandle } from 'react';
import { connect } from 'dva';
import { Row, Col, Form, Input, Select, message, Spin, InputNumber, Transfer } from 'antd';
import request from '@/utils/request';
import styles from '../styles.less';
import { getDataDictValues } from '@/utils/utils';

const { TextArea } = Input;

const formItemLayout = {
  labelCol: {
    xs: { span: 24 },
    sm: { span: 8 },
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 16 },
  },
};

const formItemLayoutText = {
  labelCol: {
    xs: { span: 24 },
    sm: { span: 4 },
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 20 },
  },
};

const namespace = 'formManage';

function AddForm(props) {
  const { getFieldDecorator } = props.form;
  const [spinning, setSpinning] = useState(false);
  const [busiCompList, setBusiCompList] = useState([]);
  const [customCompList, setCustomCompList] = useState([]);
  const [selectedKeys, setSelectedKeys] = useState([]);
  const [targetKeys, setTargetKeys] = useState([]);
  const [selectedKeysCustom, setSelectedKeysCustom] = useState([]);
  const [targetKeysCustom, setTargetKeysCustom] = useState([]);
  const [classNameList, setClassNameList] = useState([]);

  useEffect(() => {
    // 查询全部对象组件
    request('pmc/pcms/busiComponent/queryList', {
      data: {},
    }).then(res => {
      if (res && res.success === true) {
        setBusiCompList(res.data);
      } else if (res && res.errMessage) {
        message.error(res.errMessage);
      } else {
        message.error('查询对象组件失败');
      }
    });

    // 查询全部自定义组件
    request('pmc/pcms/component/queryList', {
      data: {},
    }).then(res => {
      if (res && res.success === true) {
        setCustomCompList(res.data);
      } else if (res && res.errMessage) {
        message.error(res.errMessage);
      } else {
        message.error('查询自定义组件失败');
      }
    });

    getClassNameList();
  }, []);

  useEffect(() => {
    if (props.formAddType !== 'addForm') {
      // 查询已选关联对象组件
      request('pmc/pcms/form/queryBusiCompRel', {
        data: {
          formId: props.selectForm.formId,
        },
      }).then(res => {
        if (res && res.success === true) {
          setTargetKeys(res.data);
        } else if (res && res.errMessage) {
          message.error(res.errMessage);
        } else {
          message.error('查询已选关联对象组件失败');
        }
      });

      request('pmc/pcms/form/queryCustomCompRel', {
        data: {
          formId: props.selectForm.formId,
        },
      }).then(res => {
        if (res && res.success === true) {
          setTargetKeysCustom(res.data);
        } else if (res && res.errMessage) {
          message.error(res.errMessage);
        } else {
          message.error('查询已选关联自定义组件失败');
        }
      });
    }

    if (props.formAddType === 'addForm') {
      props.form.setFieldsValue({
        catalogId: props.selectCatalog.catalogId,
        formVersionNbr: 1,
      });
    } else if (props.formAddType === 'editForm') {
      props.form.setFieldsValue({
        formId: props.selectForm.formId,
        formName: props.selectForm.formName,
        formDesc: props.selectForm.formDesc,
        catalogId: props.selectCatalog.catalogId,
        className: props.selectForm.className,
        formCode: props.selectForm.formCode,
        formType: props.selectForm.formType,
      });
    } else if (props.formAddType === 'addVersion') {
      props.form.setFieldsValue({
        formId: props.selectForm.formId,
        formName: props.selectForm.formName,
        formDesc: props.selectForm.formDesc,
        catalogId: props.selectCatalog.catalogId,
        formVersionNbr: props.addVersionNbr,
        className: props.selectForm.className,
        formCode: props.selectForm.formCode,
      });
    } else if (props.formAddType === 'editVersion') {
      props.form.setFieldsValue({
        formId: props.selectForm.formId,
        formName: props.selectForm.formName,
        formDesc: props.selectForm.formDesc,
        formVersionId: props.selectForm.formVersionId,
        formVersionNbr: props.selectForm.formVersionNbr,
        formVersionDesc: props.selectForm.formVersionDesc,
        catalogId: props.selectCatalog.catalogId,
        className: props.selectForm.className,
        formCode: props.selectForm.formCode,
      });
    }
  }, [props.formAddType]);

  const formTypeList = [
    {
      value: '1000',
      name: '流程表单',
    },
    {
      value: '1100',
      name: '普通表单',
    },
  ];

  // 获取属性值列表
  const getClassNameList = async () => {
    let temp;
    await getDataDictValues({ busiObjNbr: 'Form', attrNbr: 'CLASS_NAME' }).then(res => {
      temp = res;
    });
    setClassNameList(temp);
  };

  // 通过dva传递菜单列表数据，保存选择表单
  const saveSelectForm = params => {
    const { dispatch } = props;
    dispatch({
      type: `${namespace}/saveSelectForm`,
      payload: params,
    });
  };

  // 新增
  useImperativeHandle(props.cRef, () => ({
    handleAdd: () => {
      return new Promise(function(resolve) {
        props.form.validateFields((err, value) => {
          if (err) return;

          setSpinning(true);
          value.formVersionNbr += '';
          value.targetKeys = targetKeys;
          value.targetKeysCustom = targetKeysCustom;
          if (props.formAddType === 'addForm') {
            request('pmc/pcms/form/add', { data: value }).then(res => {
              if (res && res.success === true) {
                setSpinning(false);
                message.success('新增成功');
                resolve(true);
              } else {
                setSpinning(false);
                if (res && res.errMessage) {
                  message.error(res.errMessage);
                } else {
                  message.error('新增失败');
                }
              }
            });
          } else if (props.formAddType === 'editForm') {
            request('pmc/pcms/form/update', { data: value }).then(res => {
              if (res && res.success === true) {
                setSpinning(false);
                message.success('修改成功');
                let { selectForm } = props;
                selectForm.formName = value.formName;
                selectForm.formDesc = value.formDesc;
                selectForm.formType = value.formType;
                selectForm.className = value.className;
                saveSelectForm(selectForm);
                resolve(true);
              } else {
                setSpinning(false);
                if (res && res.errMessage) {
                  message.error(res.errMessage);
                } else {
                  message.error('修改失败');
                }
              }
            });
          } else if (props.formAddType === 'addVersion') {
            request('pmc/pcms/formVersion/add', { data: value }).then(res => {
              if (res && res.success === true) {
                setSpinning(false);
                message.success('新增成功');
                resolve(true);
              } else {
                setSpinning(false);
                if (res && res.errMessage) {
                  message.error(res.errMessage);
                } else {
                  message.error('新增失败');
                }
              }
            });
          } else if (props.formAddType === 'editVersion') {
            request('pmc/pcms/formVersion/update', { data: value }).then(res => {
              if (res && res.success === true) {
                setSpinning(false);
                message.success('修改成功');
                let { selectForm } = props;
                selectForm.formVersionNbr = value.formVersionNbr;
                selectForm.formVersionDesc = value.formVersionDesc;
                saveSelectForm(selectForm);
                resolve(true);
              } else {
                setSpinning(false);
                if (res && res.errMessage) {
                  message.error(res.errMessage);
                } else {
                  message.error('修改失败');
                }
              }
            });
          }
        });
      });
    },
  }));

  const handleChange = (nextTargetKeys, direction, moveKeys) => {
    setTargetKeys(nextTargetKeys);
  };

  const handleSelectChange = (sourceSelectedKeys, targetSelectedKeys) => {
    setSelectedKeys([...sourceSelectedKeys, ...targetSelectedKeys]);
  };

  const handleChangeCustom = (nextTargetKeys, direction, moveKeys) => {
    setTargetKeysCustom(nextTargetKeys);
  };

  const handleSelectChangeCustom = (sourceSelectedKeys, targetSelectedKeys) => {
    setSelectedKeysCustom([...sourceSelectedKeys, ...targetSelectedKeys]);
  };

  return (
    <Spin spinning={spinning}>
      <Form>
        <Row>
          <Col span={12}>
            <Form.Item label="表单名称" {...formItemLayout}>
              {getFieldDecorator('formName', {
                rules: [
                  {
                    required: true,
                    message: '表单名称不能为空',
                  },
                ],
              })(
                <Input
                  placeholder="请输入表单名称"
                  disabled={
                    props.formAddType === 'editVersion' || props.formAddType === 'addVersion'
                  }
                  maxLength={30}
                />
              )}
            </Form.Item>
          </Col>
          <Col span={12} style={{ display: props.formAddType === 'editForm' ? 'none' : '' }}>
            <Form.Item label="版本号" {...formItemLayout}>
              {getFieldDecorator('formVersionNbr', {
                rules: [
                  {
                    required: props.formAddType !== 'editForm',
                    message: '版本号不能为空',
                  },
                ],
              })(
                <InputNumber
                  className={`${styles['ant-input-number']}`}
                  precision={1}
                  min={1}
                  step={0.1}
                  defaultValue={1}
                />
              )}
            </Form.Item>
          </Col>
        </Row>
        <Row
          style={{
            display:
              props.formAddType === 'addVersion' || props.formAddType === 'editVersion'
                ? 'none'
                : null,
          }}
        >
          <Col span={12}>
            <Form.Item label="表单编码" {...formItemLayout}>
              {getFieldDecorator('formCode')(
                <Input placeholder="系统自动生成" disabled maxLength={30} />
              )}
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item label="表单类型" {...formItemLayout}>
              {getFieldDecorator('formType', {
                rules: [
                  {
                    required: !(
                      props.formAddType === 'editVersion' || props.formAddType === 'addVersion'
                    ),
                    message: '表单类型不能为空',
                  },
                ],
              })(
                <Select
                  allowClear
                  placeholder="请选择表单类型"
                  disabled={
                    !!(props.formAddType === 'editVersion' || props.formAddType === 'addVersion')
                  }
                >
                  {formTypeList.map(item => {
                    return <Select.Option value={item.value}>{item.name}</Select.Option>;
                  })}
                </Select>
              )}
            </Form.Item>
          </Col>
        </Row>
        <Row
          style={{
            display:
              props.formAddType === 'addVersion' || props.formAddType === 'editVersion'
                ? 'none'
                : null,
          }}
        >
          <Col span={24}>
            <Form.Item label="表单业务实现类" {...formItemLayoutText}>
              {getFieldDecorator('className', {
                rules: [
                  {
                    required: true,
                    message: '表单业务实现类不能为空',
                  },
                ],
              })(
                <Select
                  allowClear
                  placeholder="请选择表单业务实现类"
                  disabled={
                    !!(props.formAddType === 'editVersion' || props.formAddType === 'addVersion')
                  }
                >
                  {classNameList.map(item => {
                    return (
                      <Select.Option value={item.attrValueId}>{item.attrValueName}</Select.Option>
                    );
                  })}
                </Select>
              )}
            </Form.Item>
          </Col>
        </Row>
        <Row
          style={{
            display:
              props.formAddType === 'addVersion' || props.formAddType === 'editVersion'
                ? 'none'
                : null,
          }}
        >
          <Col span={24}>
            <Form.Item label="表单描述" {...formItemLayoutText}>
              {getFieldDecorator('formDesc')(
                <TextArea
                  rows={5}
                  placeholder="请输入表单描述"
                  disabled={
                    !!(props.formAddType === 'editVersion' || props.formAddType === 'addVersion')
                  }
                  maxLength={150}
                />
              )}
            </Form.Item>
          </Col>
        </Row>
        <Row>
          <Col span={24} style={{ display: props.formAddType === 'editForm' ? 'none' : '' }}>
            <Form.Item label="版本描述" {...formItemLayoutText}>
              {getFieldDecorator('formVersionDesc')(
                <TextArea rows={5} placeholder="请输入版本描述" maxLength={150} />
              )}
            </Form.Item>
          </Col>
        </Row>
        <Row
          style={{
            display:
              props.formAddType === 'addVersion' || props.formAddType === 'editVersion'
                ? 'none'
                : null,
          }}
        >
          <Col span={24}>
            <Form.Item label="关联对象组件" {...formItemLayoutText}>
              <Transfer
                rowKey={item => item.busiCompId}
                dataSource={busiCompList}
                showSearch
                titles={['全部对象组件', '已选对象组件']}
                targetKeys={targetKeys}
                selectedKeys={selectedKeys}
                onChange={handleChange}
                onSelectChange={handleSelectChange}
                // onScroll={handleScroll}
                render={item => `${item.busiCompCode}:${item.busiCompName}`}
                listStyle={{
                  height: 300,
                  width: '46%',
                }}
                disabled={
                  !!(props.formAddType === 'editVersion' || props.formAddType === 'addVersion')
                }
              />
            </Form.Item>
          </Col>
        </Row>
        <Row
          style={{
            display:
              props.formAddType === 'addVersion' || props.formAddType === 'editVersion'
                ? 'none'
                : null,
          }}
        >
          <Col span={24}>
            <Form.Item label="关联自定义组件" {...formItemLayoutText}>
              <Transfer
                rowKey={item => item.componentId}
                dataSource={customCompList}
                showSearch
                titles={['全部自定义组件', '已选自定义组件']}
                targetKeys={targetKeysCustom}
                selectedKeys={selectedKeysCustom}
                onChange={handleChangeCustom}
                onSelectChange={handleSelectChangeCustom}
                // onScroll={handleScroll}
                render={item => `${item.componentCode}:${item.componentName}`}
                listStyle={{
                  height: 300,
                  width: '46%',
                }}
                disabled={
                  !!(props.formAddType === 'editVersion' || props.formAddType === 'addVersion')
                }
              />
            </Form.Item>
          </Col>
        </Row>
        <Row style={{ display: 'none' }}>
          <Col span={1}>
            <Form.Item label="目录Id" {...formItemLayout}>
              {getFieldDecorator('catalogId')(<Input disabled />)}
            </Form.Item>
          </Col>
          <Col span={1}>
            <Form.Item label="表单Id" {...formItemLayout}>
              {getFieldDecorator('formId')(<Input disabled />)}
            </Form.Item>
          </Col>
          <Col span={1}>
            <Form.Item label="表单版本Id" {...formItemLayout}>
              {getFieldDecorator('formVersionId')(<Input disabled />)}
            </Form.Item>
          </Col>
        </Row>
      </Form>
    </Spin>
  );
}

export default connect(({ formManage }) => ({
  addVersionNbr: formManage.addVersionNbr,
  selectCatalog: formManage.selectCatalog,
  selectForm: formManage.selectForm,
  formAddType: formManage.formAddType,
}))(Form.create()(AddForm));
